package com.nitty.cash.loop.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.BitmapFactory
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.nitty.cash.loop.NittyApp
import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonDialog
import com.nitty.cash.loop.databinding.DialogGuideApplyBinding
import com.nitty.cash.loop.event.NittyEventPointType
import com.nitty.cash.loop.utils.NittyDensityUtil
import com.nitty.cash.loop.utils.NittyTitleBarUtil
import org.json.JSONObject
import java.math.BigDecimal

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/13 15:41
 * @Annotation：申贷引导dialog
 */
class NittyGuideApplyDialog: CommonDialog {

    private lateinit var binding: DialogGuideApplyBinding
    private var mCallback: IDialogCallback? = null

    private var countdownTimer: MyCountDownTimer? = null
    //等待时长
    private var countdown = 6
    constructor(context: Context) : super(context) {}
    constructor(context: Context, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    override fun initWindow() {
        val params = window!!.attributes
        params.width = NittyApp.app.getPhoneWidth() - NittyDensityUtil.dp2px(32f)
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(R.style.dialog_scale_anim) //修改动画样式
        window!!.setGravity(Gravity.TOP)
    }

    /**
     * 设置点击回调
     */
    fun setOnClick(callback: IDialogCallback){
        this.mCallback = callback
    }

    override fun getRootView(): View {
        binding = DialogGuideApplyBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initView() {
        val top = NittyTitleBarUtil.getStatusBarHeight()
        binding.applyGuideLayout.setPadding(0,top,0,0)
    }

    override fun initListener() {
        setOnClickListener(binding.imgApplyGuideClose) //关闭
    }

    override fun loadData() {
    }

    override fun onViewClick(v: View?) {
        dismiss()
        if(mCallback != null){
            mCallback!!.onClick(v)
        }
    }

    /**
     * 设置额度值
     */
    fun showNittyApplyGuideDatas(data: JSONObject){
        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        val minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString()
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        //设置最大值
        binding.applySeekBar.max = maxAmount.toInt()
        //设置当前值
        binding.applySeekBar.progress = amount.toInt()
        binding.applySeekBar.isEnabledDrag = false
        binding.applySeekBar.setCursorThumbBitmap(BitmapFactory.decodeResource(context.resources, R.mipmap.nitty_amount_cursor_pressed))

        binding.textApplyAmount.text = amount
        binding.textApplyMinAmount.text = minAmount
        binding.textApplyMaxAmount.text = maxAmount

        binding.imgApplyGuideClose.visibility = View.GONE
        binding.textApplyGuideCountdown.visibility = View.VISIBLE
        binding.textApplyGuideCountdown.text = "$countdown"+"S"

        startCountdownTimer()
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    /**
     * 开启倒计时
     */
    private fun startCountdownTimer(){
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val dialog: NittyGuideApplyDialog, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            dialog.countdown = (millisUntilFinished / 1000).toInt()
            dialog.showGuideCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            dialog.showGuideComplete()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showGuideCountdownText(){
        binding.textApplyGuideCountdown.text = "$countdown"+"S"
    }

    /**
     * 倒计时完成
     */
    private fun showGuideComplete(){
        binding.imgApplyGuideClose.visibility = View.VISIBLE
        binding.textApplyGuideCountdown.visibility = View.GONE
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(NittyEventPointType.DIALOG.NITTY_DIALOG_APPLY_GUIDE_SHOW)
    }

    override fun dismiss() {
        super.dismiss()
        addEventPointRequestAction(NittyEventPointType.DIALOG.NITTY_DIALOG_APPLY_GUIDE_DISMISS)
    }
}